#pragma once

#include"Common.hpp"
#include"TcpSocket.hpp"
#include"Channel.hpp"
#include"EventLoop.hpp"
class Acceptor
{
private:
    TcpSocket _socket; // ⽤于创建监听套接字
    EventLoop *_loop;  // ⽤于对监听套接字进⾏事件监控
    Channel _channel;  // ⽤于对监听套接字进⾏事件管理
    using AcceptCallback = std::function<void(int)>;
    AcceptCallback _accept_callback;

private:
    /*监听套接字的读事件回调处理函数---获取新连接，调⽤_accept_callback函数进⾏新连
   接处理*/
    void HandleRead()
    {
        int newfd = _socket.AcceptSocket();
        if (newfd < 0)
        {
            return;
        }
        if (_accept_callback)
        {
            _accept_callback(newfd);
        }
    }
    int CreateServer(int port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret != false);
        return _socket.SockFd();
    }

public:
    Acceptor(EventLoop *loop, uint16_t port) : _socket(CreateServer(port)),
                                               _loop(loop),
                                               _channel(loop, _socket.SockFd())
    {
        _channel.SetReadCallback(std::bind(&Acceptor::HandleRead, this));
    }
    void SetAcceptCallback(const AcceptCallback &cb)
    {
        _accept_callback = cb;
    }
    void Listen()
    {
        _channel.OpenReadEventMonitoring();
    }
};